var bt = baidu.template;
var Page = {
    header:$('#nav'),
    headerMask: $('#header-mask'),
    navList: $('#nav a'),
    contentList: $('#nav .category-wrapper'),
    productList : $('#product-list'),
    emptyList : $('#empty-list'),
    url : '/tp/products/',
    page : 1,
    navShowed : false,
    itemClick : false,
    scroll2 : '',
    countryList : [],
    initHeader :function(){
        //顶部菜单点击
        var currentContent = {},
            _self = this;

        var scroll;

        _self.navList.on('touchstart',function(){

            // 获取目的地数据
            if ( _self.countryList.length === 0 ) {
                _self.getCountry();
            }

            if($(this).hasClass('cur')){
                $(this).removeClass('cur');
                _self.contentList.filter('.show').removeClass('show');
                _self.headerMask.removeClass('show');

                $('body').off('touchmove',offMove);
                scroll && scroll.destroy();
                _self.navShowed = false;
            }else{
                _self.navShowed = true;
                _self.navList.filter('.cur').removeClass('cur');
                $(this).addClass('cur');
                _self.headerMask.addClass('show');

                var type = $(this).data('type'),
                    lastContent = _self.contentList.filter('.show');

                currentContent = _self.contentList.filter('[data-type='+type+']');
                lastContent.removeClass('show');
                currentContent.addClass('show');

                $('body').on('touchmove',offMove);

                type = $(this).data('type');
                if ( type == 'dest' ) {
                    scroll = new iScroll('dest-wrapper-1');
                }else{
                    scroll = new iScroll(type + '-wrapper');
                }
            }
        });

        // hide menu when click header mask
        _self.headerMask.on('click', function(e) {
            e.preventDefault();
            if ( _self.navShowed ) {
                _self.navList.filter('.cur').trigger('touchstart');
            }
        });
        
        function offMove(e){
            if(e.target == currentContent.get(0) || $.contains(currentContent.get(0),e.target)){
                return;
            }else{
                e.preventDefault();
            }
        }
        // var wrapperHeight = $(window).height()-this.header.height();
        // _self.contentList.each(function(index,item){
        //     $(item).css('maxHeight',wrapperHeight);
        // });
    },
    setCountDown: function ( time, $dom ) {
        var _self = this;
        // var _obj = {
        //     product: id,
        //     sec: document.getElementById("sec-"+id),
        //     mini: document.getElementById("mini-"+id),
        //     hour: document.getElementById("hour-"+id),
        //     day: document.getElementById("day-"+id)
        // };
        _self.fnTimeCountDown(time, $dom);
    },
    handleDOM: function() {
        var _self = this;
        var _li = $('#product-list').find('li');
        // $.each(_li, function(i, val) {
        //     if ( $(this).data('time') ) {
        //         // 产品库存为 0，抢购结束
        //         // console.log($(this).find('.countdown').data('end'), 888888)
        //         if ( $(this).find('.countdown').data('end') == 1 ) {
        //             $(this).find('.countdown').find('p').html('抢购结束');
        //         }else{
        //            var _id = $(this).data('id'),
        //             _time = $(this).data('time') * 1000;
        //             _self.setCountDown( _time, $(this) ); 
        //         }
                
        //         $(this).find('.countdown p').removeClass('hide');
        //     }else{
        //         $(this).find('.countdown').hide();
        //     }
        // });
        //为防止穿透，在ajax数据渲染之后再进行事件绑定，并判断导航列表是否展现
        setTimeout(function(){
            $.each(_li, function(i, val) {
                var item = $(this);
                if(item.data('binded')){
                    return;
                }
                item.on('click',function(e){
                    if(_self.navShowed || _self.itemClick){
                        return;
                    }
                    var _url = $(this).data('url');
                    btAppSchema.jumpToWebView(_url);
                }).on('touchstart',function(e){
                    if(_self.navShowed && !_self.itemClick){
                        _self.navList.filter('.cur').trigger('touchstart');
                        return false;
                    }
                    return true;
                    
                }).data('binded',1);
            });
            
        },500);
    },
    fnTimeCountDown: function(d, $o) {
        var f = {
            zero: function(n) {
                var n = parseInt(n, 10);
                if (n > 0) {
                    if (n <= 9) {
                        n = "0" + n;
                    }
                    return String(n);
                } else {
                    return "00";
                }
            },
            dv: function() {
                d = d || Date.UTC(2050, 0, 1);
                var future = new Date(d),
                    now = new Date();
                //现在将来秒差值
                var dur = Math.round((future.getTime() - now.getTime()) / 1000),
                    pms = {
                        sec: "00",
                        mini: "00",
                        hour: "00",
                        day: "00",
                        month: "00",
                        year: "0"
                    };
                if (dur > 0) {
                    pms.sec = f.zero(dur % 60);
                    pms.mini = Math.floor((dur / 60)) > 0 ? f.zero(Math.floor((dur / 60)) % 60) : "00";
                    pms.hour = Math.floor((dur / 3600)) > 0 ? f.zero(Math.floor((dur / 3600)) % 24) : "00";
                    pms.day = Math.floor((dur / 86400)) > 0 ? f.zero(Math.floor((dur / 86400))) : "00";
                }else if(dur < 0 && $o.find('.countdown').hasClass('countdown-seckill') ){
                    $o.find('.seckill').html('抢购正在进行中');
                    return;
                }
                return pms;
            },
            ui: function() {
                var $p = $o.find('.seckill'),
                    text = "距离抢购开始还剩：",
                    time ;
                if(f.dv()){
                    if (f.dv().day != "00") {
                        time = f.dv().day + '天' + f.dv().hour + '小时' + f.dv().mini + '分' + f.dv().sec + '秒';
                    }else if(f.dv().hour != "00"){
                        time = f.dv().hour + '小时' + f.dv().mini + '分' + f.dv().sec + '秒';
                    }else if(f.dv().mini != "00"){
                        time = f.dv().mini + '分' + f.dv().sec + '秒';
                    }else{
                        time = f.dv().sec + '秒';
                    }

                    $p.html(text + time);

                    setTimeout(f.ui, 1000);
                }
                
            }
        };
        f.ui();
    },
    topSlider : function () {
        var slider = new Swiper('.swiper-container', {
            mode: 'horizontal',
            loop: true,
            autoplay: 3000,
            pagination: '.swiper-pagination',
            onTouchStart: function(){
                setTimeout(function(){
                    slider.startAutoplay();
                }, 3000);
            },
            onSlideClick:function(swiper){
                var url = $(swiper.clickedSlide).data('url');
                btAppSchema.jumpToWebView(url);
            }
        });
    },
    initItemSelector : function(){
        var _self = this;
        _self.header.on('click', 'li',function(){
            _self.itemClick = true;
            var parent = $(this).parent('ul'),
                type = parent.parents('.category-wrapper').data('type'),
                currentNav = _self.navList.filter('[data-type='+type+']'),
                isCategoryTitle = parent.parent().hasClass('category-title'),
                value = $(this).attr('data-value'),
                text = $(this).html();
            if ( isCategoryTitle && text != '全部' ) {
                // 过滤目的地一级菜单
                _self.showCountry(value);
                $(this).addClass('cur').siblings('li').removeClass('cur');
                return;
            }else{
                if( text.indexOf('全部') < 0 ){
                    currentNav.html(text + (type=='depart'?'出发':''));
                }else{
                    if ( isCategoryTitle ) {
                       $('#dest-wrapper-2 ul').html('<li data-value="" class="cur">全部目的地</li>'); 
                    }
                    if ( value == '' ) {
                        currentNav.html('全部');
                    } else{
                        currentNav.html(value)
                    }
                }
                //百度统计，筛选tab点击量
                currentNav.data('value',$(this).data('value')).trigger('touchstart');
                parent.find('.cur').removeClass('cur');
                $(this).addClass('cur');
                _self.getProduct(true);
            }
            _hmt.push(['_trackEvent', '旅游产品列表tab-' + currentNav.data('title'), 'click', '旅游产品列表tab-' + currentNav.data('title') + '-' + $.trim(text)]);
        });
    },
    getCountry : function (area) {
        var _self = this;
        var _url = '/tp/get_country/';
        $.ajax({
            url: _url,
            type: 'GET',
            dataType: 'json',
            data: {area: area},
            success: function (data) {
                if ( !area ) {
                    _self.countryList = data.data;
                }
            }
        });
    },
    showCountry : function (area) {
        var _self = this;
        var _country = _self.countryList[area];
        var _list = '<li data-value="'+ area +'">全部</li>';
        $(_country).each(function(i, val) {
            _list += '<li data-value="' + val + '">' + val + '</li>';
        });
        _self.scroll2 && _self.scroll2.destroy();
        $('#dest-wrapper-2 ul').html(_list);
        _self.scroll2 = new iScroll('dest-wrapper-2');
    },
    triggerBanner: function () {
        var banner = $('#slider'),
            category = $('#category').data('value'),
            dest = $('#dest').data('value'),
            start = $('#start').data('value'),
            depart = $('#depart').data('value');
        if ( category == '' && dest == '' && start == '' && depart == '' ) {
            banner.show();
        } else{
            banner.hide();
        };
    },
    getProduct : function(reload){
        var _self = this;
        if(reload){
            _self.page = 1;
            _self.emptyList.hide();
            _self.productList.empty();
            $('section')[0].scrollTop = 0;
            $('#loading-more').show();
            _self.triggerBanner();
        }
        $.get(_self.url, {
            category : $('#category').data('value'),
            dest : $('#dest').data('value'),
            start : $('#start').data('value'),
            depart : $('#depart').data('value'),
            page : _self.page
        },function(data) {
            //  第一次加载就没数据
            if(reload && data.products.length == 0){
                _self.productList.hide().empty();
                $('#loading-more').hide();
                _self.emptyList.fadeIn();
                $('section').off('scroll', _self.loadMoreProducts());
            }else{

                if(data.has_more){
                    _self.page = data.next_page;
                    $('section').on('scroll', _self.loadMoreProducts());
                    $('#loading-more').show();
                }else{
                    _self.page = '';
                    $('section').off('scroll', _self.loadMoreProducts());
                    $('#loading-more').hide();
                }
                _self.emptyList.hide();

                var content = bt('product_template', {list: data.products});
                if(reload){
                    _self.productList.hide().empty().append(content).fadeIn();
                }else{
                    _self.productList.append(content);
                }
                _self.handleDOM();
                
            }
            _self.itemClick = false;
        });
    },
    loadMoreProducts : function(){
        var _self = this;
        this.loadHandel = this.loadHandel || function(e){
            var box = $('section');
            var reachBottom = box[0].scrollTop + box.height() >= box[0].scrollHeight - 200; 

            if( reachBottom ) {
                $('section').off('scroll',_self.loadMoreProducts());
                _self.getProduct(false);
            }
            
        };
        return this.loadHandel;
    },
    initEmptyList : function(){
        this.emptyList.css('top',($(window).height()-this.header.height()-300)/2);
    },
    initSearchParam :function(){

        var _self = this;
        $.each(['category','dest','start','depart'],function(index,item){
            var value = getQuery(item);
            if(value){
                value = decodeURIComponent(value);
                var selectItem = _self.contentList.filter('[data-type="'+item+'"]').find('li[data-value="'+value+'"]');
                if(selectItem.length > 0){
                    $('#'+item).data('value',value).html(selectItem.html() + (item=='depart'?'出发':''));
                    selectItem.addClass('cur');
                }
            }
        });
        function getQuery(query){
            var pos = 0,params,match,kvs;
            if((pos = location.search.indexOf("?")) === -1)
                return null;
            else{
                params = location.search.substr(pos+1).split("&");
                for(var i=0;i<params.length;i++){
                    kvs = params[i].split("=");
                    if(kvs[0] == query){
                        return kvs[1] || "";
                    }
                }
            }
            return null;
        }
    },
    goHref : function(){
        $('.swiper-slide').on('click', function(){
            var url = $(this).data('url');
            btAppSchema.jumpToWebView(url);
        });
    }
}
$(function(){

    if(BT.context('banners') == 'true'){
        Page.topSlider();
    }else{
        Page.goHref();
    }
    Page.initHeader();
    Page.initItemSelector();
    Page.initEmptyList();
    Page.initSearchParam();
    Page.getProduct(true);
});